package com.tlgen.coopera.controller;

import com.alibaba.fastjson.JSONObject;
import com.tlgen.coopera.model.RegistryServer;
import com.tlgen.coopera.comon.R;
import com.tlgen.coopera.factory.RegistryLocalFactory;
import com.tlgen.coopera.service.RegistryService;
import com.tlgen.coopera.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/*
 *@title DistroController
 *@description
 *@author ta151486
 *@version 1.0
 *@create 2023/12/12 18:23
 */
@RestController
@RequestMapping("/registry")
public class RegistryController {

    @Autowired
    private RegistryService registryService;

    @PostMapping("/receive")
    public R receive(@RequestBody List<RegistryServer> registryList, HttpServletRequest request) {
        String serverPort = request.getRemoteHost() + ":" + request.getServerPort();
        System.out.println("已同步来自 " + serverPort + " 的数据: " + JSONObject.toJSONString(registryList));
        registryService.saveToLocalInstance(registryList);
        return R.ok("SUCCESS");
    }

    @GetMapping("/update")
    public R test() {
        List<RegistryServer> registryList = new ArrayList<>();

        RegistryServer registryData = new RegistryServer();
        registryData.setIp("192.168.1.4");
        registryData.setName("my-test");
        registryData.setPort(9994);
        registryData.setTime(DateUtils.LocalDateTimeToString(LocalDateTime.now()));

        RegistryServer registryData2 = new RegistryServer();
        registryData2.setIp("192.168.1.4");
        registryData2.setName("my-test2");
        registryData2.setPort(9995);
        registryData2.setTime(DateUtils.LocalDateTimeToString(LocalDateTime.now()));

        registryList.add(registryData);
        registryList.add(registryData2);

        RegistryLocalFactory.getInstance().setRegistryList(registryList);

        registryService.updateToLocalInstance(registryList);

        return R.ok("SUCCESS");
    }

    @GetMapping("/select")
    public R select() {
        return R.ok(RegistryLocalFactory.getInstance().getRegistryList(), "SUCCESS");
    }

    @PostMapping("/doRegistry")
    public R doRegistry(@RequestBody RegistryServer registryServer) {
        registryService.doRegistry(registryServer);
        return R.ok("SUCCESS");
    }

}
